import useRequest from "@/app/utils/axiosRequest";
import {decodeFromBase64} from "next/dist/build/webpack/loaders/utils";
import cookie from "react-cookies";
import {UserName} from "@/app/constants/authTokenConstants";
import ToastUtil from "@/app/utils/toastUtil";

export default async function UploadFileService(files: any, callback: any) {
    const axiosInstance = useRequest();
    const res = await Promise.all(
        files.map((file: File) => {
            return new Promise((rev, rej) => {
                const form = new FormData();
                form.append('file', file);
                axiosInstance.post('/note/minio/upload', form, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    params: {
                        "noteId": decodeFromBase64(cookie.load(UserName)),
                        "username": decodeFromBase64(cookie.load(UserName))
                    }
                })
                    .then((res) => {
                            console.log(res)
                            if (res.data.status) {
                                rev(res);
                            } else {
                                ToastUtil(res.data.message, "🫱", "error");
                            }
                        }
                    )
                    .catch((error) => rej(error));
            });
        })
    );
    callback(res.map((item) => item.data.data.url));
}